from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from django.core.urlresolvers import reverse
import logging
from controlpanel.models import Entity, Object, ObjectField

logger = logging.getLogger(__name__)

def index(request):
    
    return HttpResponse("This is the front page of the system. There is nothing here yet.")

def form(request, obj_name, obj_id):
    
    # TODO: Check if object type exists
    
    obj = Object.objects.get(name=obj_name)
    fields = ObjectField.objects.filter(object__exact=obj.id)
    
    # TODO: Get content
    #sql = "SELECT * FROM " + obj_name + " WHERE id=" + obj_id
    
    context = {'new': False, 'obj_name': obj_name, 'fields': fields}
    return render(request, 'form.html', context)

def new_form(request, obj_name):
    logger.debug('Displaying form to create new object of type ' + obj_name)
    
    # TODO: Test if object type exits
    
    obj = Object.objects.get(name__iexact=obj_name) # case in-sensitive
    
    fields = ObjectField.objects.filter(object__exact=obj.id)
    context = {'new': True, 'obj_name': obj_name, 'fields': fields}
    return render(request, 'form.html', context)


def save_form(request):
    
    for i in request.POST:
        logger.debug(i)
    
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))